#include "delay.h"	
#include "SWM320.h"	   
static uint32_t tick=0;
//20000000/1000000=20;
static uint32_t reload=1000000;

//systick�жϷ�����,ʹ��ucosʱ�õ�
// void SysTick_Handler(void)
// {
	
// 	// printf("tick %d\r\n",tick);
// 	// if(--tick <= 0)
// 	// {
// 	// 	// NVIC_DisableIRQ(SysTick_IRQn);s
// 	// }
	
// }


// void delay_init(void)
// {
// 	SysTick_Config(SystemCoreClock/reload);			//SystemCoreClock/4=0.25s
// }								    

//��ʱnus
//nusΪҪ��ʱ��us��.		    								   
void delay_us(uint32_t nus)
{
	uint32_t temp;
	//20000
	// if ((uint32_t)(SystemCoreClock/reload-1UL)*nus > SysTick_LOAD_RELOAD_Msk)
	// {
	// 	return;
	// 	// return (1UL);                                                   /* Reload value impossible */
	// }
	// SysTick->LOAD = (uint32_t)(SystemCoreClock/reload-1UL)*nus;
	// // printf("SysTick->LOAD %d\r\n",SysTick->LOAD);
	// NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */
 
	// SysTick->VAL   = 0UL;                                             /* Load the SysTick Counter Value */
  	// SysTick->CTRL  = SysTick_CTRL_CLKSOURCE_Msk |
    //                SysTick_CTRL_TICKINT_Msk   |
    //                SysTick_CTRL_ENABLE_Msk;                         /* Enable SysTick IRQ and SysTick Timer */
	// do
	// {
	// temp=SysTick->CTRL;//读取当前倒计数值
	// // printf("SysTick->CTRL %d\r\n",SysTick->CTRL);
	// }while((temp&0x01)&&(!(temp&(1<<16))));//等待时间到达
	// SysTick->CTRL=0x00; //关闭计数器
	// SysTick->VAL =0X00; //清空计数器
	
    uint32_t tcnt = 0,tnow,told;
	told = SysTick->VAL;
	while(1)
	{
		tnow = SysTick->VAL;
		if(tnow == told){
			continue;
		}
		// printf("SysTick->LOAD %lu SystemCoreClock/reload %lu\r\n",SysTick->LOAD,SystemCoreClock/reload);
		if(tnow>told)
		{
			tcnt+=told+(SysTick->LOAD-tnow);
			// printf("tnow %lu told %lu tcnt+= %lu\r\n",tnow,told,told+(SysTick->LOAD-tnow));
		}else{
			tcnt+=told-tnow;
			// printf("tnow %lu told %lu tcnt+= %lu\r\n",tnow,told,told-tnow);
		}
		// printf("(nus %lu nus*SystemCoreClock/reload) %lu tcnt= %lu\r\n",nus,(nus*(SystemCoreClock/reload)),tcnt);
		told=tnow;
		if(tcnt >= (nus*(SystemCoreClock/reload)))
			break;
	}

}

void delay_ms(unsigned int nms)
{	unsigned int i = nms;
    while(i--)
	{
        delay_us(1000UL);
	}
	    
}

